package com.hjj.jvm.oom;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * <h2>本机直接内存溢出</h2>
 * <p>VM Args: -Xmx20M -XX:MaxDirectMemorySize=10M</p>
 */
public class DirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) {
        try {
            Field[] declaredFields = Unsafe.class.getDeclaredFields();
            Field unsafeField = declaredFields[0];
            unsafeField.setAccessible(true);
            Unsafe unsafe = (Unsafe) unsafeField.get(null);
            while (true) {
                unsafe.allocateMemory(_1MB);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
